//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by FernFlower decompiler)
//

package org.springframework.security.oauth2.server.authorization.authentication;

import java.time.Duration;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.*;
import com.mdp.core.SpringUtils;
import com.mdp.safe.client.entity.CommonUserDetails;
import com.mdp.safe.client.entity.SafeAuthority;
import com.mdp.safe.client.entity.User;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.keygen.Base64StringKeyGenerator;
import org.springframework.security.crypto.keygen.StringKeyGenerator;
import org.springframework.security.oauth2.core.OAuth2RefreshToken;
import org.springframework.security.oauth2.core.OAuth2RefreshToken2;
import org.springframework.security.oauth2.jose.JoseHeader;
import org.springframework.security.oauth2.jose.jws.SignatureAlgorithm;
import org.springframework.security.oauth2.jwt.Jwt;
import org.springframework.security.oauth2.jwt.JwtClaimsSet;
import org.springframework.security.oauth2.jwt.JwtEncoder;

/**
 * 增加 userInfo 扩展字段，userInfo=username|tpaOpenid|maxDataLvl|deptids|deptname|branchIds|branchName 分别为 用户中文名称|第三方登录编号|最高数据访问等级|部门编号|部门名称|机构编号|机构名称
 * 增加 roles扩展字段 ， roles=role1|role2|role3等 ,多个角色用|进行分割，每个角色包含 role= roleid,rolename,dataLvl
 */
class OAuth2TokenIssuerUtil {
    private static final StringKeyGenerator TOKEN_GENERATOR = new Base64StringKeyGenerator(Base64.getUrlEncoder().withoutPadding(), 96);

    OAuth2TokenIssuerUtil() {
    }
    static Jwt issueJwtAccessToken(JwtEncoder jwtEncoder, String subject, String audience, Set<String> scopes) {
        JoseHeader joseHeader = JoseHeader.withAlgorithm(SignatureAlgorithm.RS256).build();
        /**
         URL issuer = null;

         try {
         issuer = URI.create("www.qingqinkj.com").toURL();
         } catch (MalformedURLException var9) {
         }
         **/
        String userInfo="";
        String roles="";
        if(!subject.equals(audience)){
            UserDetailsService userDetailsService= SpringUtils.getBean(UserDetailsService.class);
            CommonUserDetails userDetail = (CommonUserDetails) userDetailsService.loadUserByUsername(subject);
            
            if(userDetail==null){
                userInfo="";
            }else{
                User user=userDetail.getUser();
                userInfo= user.toSimpleString();
                Collection<GrantedAuthority> gas= (Collection<GrantedAuthority>) userDetail.getAuthorities();
                roles = SafeAuthority.toRolesString(gas);
            }
            
        }
        Instant issuedAt = Instant.now();
        Instant expiresAt = issuedAt.plus(2, ChronoUnit.DAYS);
        JwtClaimsSet jwtClaimsSet = JwtClaimsSet.withClaims().subject(subject).audience(Collections.singletonList(audience)).issuedAt(issuedAt).expiresAt(expiresAt).notBefore(issuedAt).claim("scope", scopes).claim("userInfo",userInfo).claim("roles",roles).build();
        return jwtEncoder.encode(joseHeader, jwtClaimsSet);
    }

    static Jwt issueJwtAccessToken(JwtEncoder jwtEncoder, UsernamePasswordAuthenticationToken subject, String audience, Set<String> scopes) {
        JoseHeader joseHeader = JoseHeader.withAlgorithm(SignatureAlgorithm.RS256).build();
        /**
         URL issuer = null;

         try {
         issuer = URI.create("www.qingqinkj.com").toURL();
         } catch (MalformedURLException var9) {
         }
         **/
        String userInfo="";
        String roles="";
        if(!subject.getName().equals(audience)){

            CommonUserDetails userDetail = (CommonUserDetails) subject.getPrincipal();

            if(userDetail==null){
                userInfo="";
            }else{
                User user=userDetail.getUser();
                userInfo= user.toSimpleString();
                Collection<GrantedAuthority> gas= (Collection<GrantedAuthority>) userDetail.getAuthorities();
                roles = SafeAuthority.toRolesString(gas);
            }

        }
        Instant issuedAt = Instant.now();
        Instant expiresAt = issuedAt.plus(2, ChronoUnit.DAYS);
        JwtClaimsSet jwtClaimsSet = JwtClaimsSet.withClaims().subject(subject.getName()).audience(Collections.singletonList(audience)).issuedAt(issuedAt).expiresAt(expiresAt).notBefore(issuedAt).claim("scope", scopes).claim("userInfo",userInfo).claim("roles",roles).build();
        return jwtEncoder.encode(joseHeader, jwtClaimsSet);
    }

    static OAuth2RefreshToken issueRefreshToken(Duration refreshTokenTimeToLive) {
        Instant issuedAt = Instant.now();
        Instant expiresAt = issuedAt.plus(refreshTokenTimeToLive);
        return new OAuth2RefreshToken2(TOKEN_GENERATOR.generateKey(), issuedAt, expiresAt);
    }

    public static void main(String[] args) {
        String ext="%s|%s|%s|%s|%s|%s|%s|||";
        Set<String> deptids=new HashSet<>();
        deptids.add("deptids001");
        deptids.add("deptids002");
        String.join(",",deptids);
        ext= String.format(ext,"陈育才","chenyc-001","1",String.join(",",deptids),"部门名称","机构列表","机构名称");
        System.out.printf("ext--->"+ext);

        String[] exts=ext.split("\\|",-1);
        System.out.println(String.join("$",exts));

    }
    public static String notNullStr(String value,String defaultValue){
        if(value==null){
            return defaultValue;
        }else return value;
    }
    public static Integer notNullInteger(Object value,Integer defaultValue){
        if(value==null){
            return defaultValue;
        }else {
            if(value instanceof Integer){
                return (Integer) value;
            }else {
                return Integer.parseInt(value.toString());
            }
        }
    }
    public static String join(Set<String> value,String defaultValue){
        if(value==null || value.isEmpty()){
            return defaultValue;
        }else {
            return String.join(",",value);
        }
    }
}
